package com.hust360.percent.utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import android.os.Environment;

public class StorageUtils {
	
	/**
	 * 用来把date类型转换成为可以插入数据作为datetime类型的
	 * DateFormat
	 */
	public static SimpleDateFormat simpleDateFormat =  new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	/**
	 * 数据（图片、离线数据库等） 在sd卡中的基本目录
	 */
	public static final String SDCARD_BASE_FOLDER = "com.hust.percent";

	/**
	 * 图片存放的目录
	 */
	public static final String SDCARD_IMG_FOLDER = SDCARD_BASE_FOLDER
			+ File.separator + "image";
	
	/**
	 * sd卡中数据的名字
	 */
	public static final String SDCARD_DB_NAME = "local_db";

	/**
	 * sd卡上的数据的配置 最大id.etc;
	 */
	public static final String SD_PROPERTY = "local_db_property";

	/**
	 * 当前最大的店铺id
	 */
	public static long curMaxShopId = 0;

	/**
	 * 当前最大的discountInfo的ID
	 */
	public static long curMaxDiscountId = 0;
	
	/**
	 * 区域最大的id
	 */
	public static long curMaxAreaId = 0;

	/**
	 * curMaxDiscountId的键
	 */
	public static final String CUR_MAX_DISCOUNT_ID_KEY = "CUR_MAX_DISCOUNT_ID_KEY";

	/**
	 * curMaxShopId的键
	 */
	public static final String CUR_MAX_SHOP_ID_KEY = "CUR_MAX_SHOP_ID_KEY";

	/**
	 * 获取sd卡的根目录，如果sd卡不存在，则抛出一个异常
	 * 
	 * @return sd卡的根目录
	 * @throws Exception
	 */
	public static String getSDPath() throws IOException {
		File sdDir = null;
		boolean hasSDCard = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
		if (hasSDCard) {
			sdDir = Environment.getExternalStorageDirectory();
			return sdDir.getAbsolutePath();
		} else
			throw new IOException("sd card is not exist");
	}

	/**
	 * 创建sd上存放数据的文件夹和文件
	 * 
	 * @throws Exception
	 */
	public static void buildLocalDataDirectory() throws IOException {
		String sdcardPath = getSDPath();
		File baseFile = new File(sdcardPath + File.separator
				+ SDCARD_BASE_FOLDER);
		if (!baseFile.isDirectory()) {
			baseFile.mkdir();
		}
		File local_db_file = new File(baseFile.getAbsolutePath()
				+ File.separator + SDCARD_DB_NAME);
		if (!local_db_file.isFile()) {
			local_db_file.createNewFile();
		}
		File imageFolder = new File(getSDPath() + File.separator + SDCARD_IMG_FOLDER);
		if (!imageFolder.isDirectory()) {
			imageFolder.mkdir();
		}
		File file = new File(sdcardPath + File.separator + "file/");
		if (file.isDirectory()) {
			FileUtils.deleteDir(file);
			file.mkdir();
		}else  if (file.isFile()) {
			file.delete();
			file.mkdir();
		}
		else {
			file.mkdir();
		}
		
		file = new File(sdcardPath + File.separator + "area_file");
		if (file.isDirectory()) {
			FileUtils.deleteDir(file);
			file.mkdir();
		}else  if (file.isFile()) {
			file.delete();
			file.mkdir();
		}
		else {
			file.mkdir();
		}
	}
}
